﻿using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command.MenuCommand;
using B.S.DataBase.MyRead.API.DTOs;
using MediatR;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler.MenuCommandHandler
{
    /// <summary>
    /// 菜单列表命令执行
    /// </summary>
    public class GetMenuCommandHandler : IRequestHandler<GetMenuCommand, APIResult<List<MenuDTOs>>>
    {
        private readonly IBaseRepository<MenuModel> menuRepos;

        public GetMenuCommandHandler(IBaseRepository<MenuModel> menuRepos)
        {
            this.menuRepos = menuRepos;
        }

        /// <summary>
        /// 菜单列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<List<MenuDTOs>>> Handle(GetMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<MenuDTOs>> result = new APIResult<List<MenuDTOs>>();
            var list = from a in menuRepos.GetAll().Result
                       join b in menuRepos.GetAll().Result on a.ParentId equals b.MenuId
                       where a.IsDeleted == false
                       select new MenuDTOs
                       {
                           MenuId = a.MenuId,
                           MenuName = a.MenuName,
                           Url = a.Url,
                           ParentId = a.ParentId,
                           CreateName = a.CreateName,
                           CreateTime = a.CreateTime,
                           UpdateName = a.UpdateName,
                           UpdateTime = a.UpdateTime,
                           IsDeleted = a.IsDeleted,
                           ParentName = b.MenuName,
                           OrderNum = a.OrderNum,
                       };
            result.data = list.OrderByDescending(x=>x.MenuId).ToList();
            return await Task.FromResult(result);
        }
    }
}
